package cn.laixueit.controller;

import cn.laixueit.pojo.Category;
import cn.laixueit.result.Result;
import cn.laixueit.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list/{parentid}")
    private List<Category> list(@PathVariable("parentid")Integer pid,String name){
        return categoryService.list(pid,name);
    }

    @PostMapping("/save")
    public Result save(@RequestBody Category category){
        try {
            categoryService.save(category);
            return new Result();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(400,null);
        }
    }

    @PostMapping("/update")
    public Result update(@RequestBody Category category){
        try {
            categoryService.update(category);
            return new Result();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(400,null);
        }
    }

    @GetMapping("/findById/{id}")
    public Result findById(@PathVariable("id")Integer id){
        Category category = categoryService.findById(id);
        if(category == null){
            return new Result(400,null);
        }
        return new Result(200,category);
    }


    @GetMapping("/del/{id}")
    public Result del(@PathVariable("id")Integer id){
        Category category = categoryService.delById(id);
        if(category != null){
            return new Result(400,"具备下级分类，不可删除");
        }
        return new Result(200,"删除成功");
    }


    @GetMapping("/findCategoryListMap")
    public List<Map<String, Object>> findCategoryListMap(){
        List<Map<String, Object>> listMap = categoryService.findCategoryListMap();
        return listMap;
    }


}
